package com.tacademy.android.lbs.friend;

import java.util.ArrayList;
import java.util.List;

import org.restlet.data.CharacterSet;
import org.restlet.data.Language;
import org.restlet.data.MediaType;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.ServerResource;
import org.restlet.representation.StringRepresentation;
import org.restlet.representation.Variant;

import com.google.gson.Gson;
import com.tacademy.android.lbs.friend.model.UserLocation;
import com.tacademy.android.lbs.friend.model.UserLocationOutput;

public class FriendRestlet extends ServerResource {
	FriendDAO friendDAO = new FriendDAO();
	Gson gson = new Gson();
	
	@Get
	public Representation toJson(Variant variant) {
		Representation result = null;
		String friendId = (String)getRequest().getAttributes().get("friend_id");
		
    	if (friendId != null) {
    		UserLocation friendLocation = friendDAO.selectUserByUserId(friendId);
    		if (friendLocation != null) {
        		result = new StringRepresentation(gson.toJson(new UserLocationOutput(friendLocation)), MediaType.TEXT_PLAIN, Language.ALL, CharacterSet.UTF_8);
    		}
    	} else { //all
    		List<UserLocation> friends = friendDAO.selectUserList();
    		List<UserLocationOutput> friendsOutput = new ArrayList<UserLocationOutput>();
    		for (UserLocation friendLocation : friends) {
    			friendsOutput.add(new UserLocationOutput(friendLocation));
    		}
			result = new StringRepresentation(gson.toJson(friendsOutput), MediaType.TEXT_PLAIN, Language.ALL, CharacterSet.UTF_8);
    	}
        return result;
	}
}
